package com.itheima.user.service;

import com.heima.common.cache.CacheService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.itheima.user.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author 大可
 * @date 2022/7/28 10:49
 */
@Service
@Slf4j
public class ApUserRelationServiceImpl implements ApUserRelationService{

    @Autowired
    private CacheService cacheService;

    @Override
    public ResponseResult follow(UserRelationDto dto) {
        if (dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //检测用户是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        Integer userId = user.getId();
        Integer authorId = dto.getAuthorId();

        Short operation = dto.getOperation();
        if (0 == operation){
            cacheService.zAdd(BehaviorConstants.APUSER_FOLLOW_RELATION + userId,authorId.toString(),System.currentTimeMillis());
            cacheService.zAdd(BehaviorConstants.APUSER_FANS_RELATION + authorId,userId.toString(),System.currentTimeMillis());
        }else {
            cacheService.zRemove(BehaviorConstants.APUSER_FOLLOW_RELATION + userId,authorId.toString());
            cacheService.zRemove(BehaviorConstants.APUSER_FANS_RELATION + authorId,userId.toString());
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
